package com.turing.system.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.turing.system.entity.Admin;
import com.turing.system.mapper.KeeperWithdrawalsMapper;
import com.turing.system.service.AdminService;
import com.turing.system.mapper.AdminMapper;
import enums.ErrorCode;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import result.Result;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @author 28123
 * @description 针对表【admin(管理员)】的数据库操作Service实现
 * @createDate 2023-05-09 14:50:57
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
        implements AdminService {

    @Resource
    private KeeperWithdrawalsMapper keeperWithdrawalsMapper;

    @Override
    public Result query(String account, String rankId, Integer pageNum, Integer pageSize) {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<Map<String, Object>> list = super.baseMapper.query(account, rankId);
        if (list.size() > 0) {
            return Result.success(new PageInfo<>(list));
        } else {
            return Result.fail(0, "无数据");
        }
    }

    @Override
    public Result getDetail(Integer id) {
        if (id == null) {
            return Result.fail(0,"用户不存在");
        }
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(true, Admin::getUserId, id).last("limit 1");
        Admin admin = this.baseMapper.selectOne(wrapper);
        if (admin!=null){
            map.put("userId", admin.getUserId());
            map.put("loginAccount", admin.getLoginAccount());
            map.put("status", admin.getStatus());
            map.put("phone", admin.getPhone());
            map.put("rankId", admin.getRankId());
            return Result.success(map);
        }else {
            return Result.fail(0,"用户不存在");
        }

    }

    /**
     * 添加管理员
     *
     * @param jsonObject
     * @return
     * @throws ParseException
     */
    @Override
    public Result addSave(JSONObject jsonObject) throws ParseException {

        String loginAccount = jsonObject.getString("loginAccount");
        String phone = jsonObject.getString("phone");
        String rankId = jsonObject.getString("rankId");
        if (Strings.isEmpty(loginAccount) && Strings.isEmpty(phone) && Strings.isEmpty(rankId)) {
            return Result.fail(0,"无需要添加的数据");
        }
        if (StringUtils.isEmpty(loginAccount)){
            return Result.fail(0,"账户不能为空");
        }
        if (StringUtils.isEmpty(phone)){
            return Result.fail(0,"手机号不能为空");
        }
        if (StringUtils.isEmpty(rankId)){
            return Result.fail(0,"角色不能为空");
        }
        //判断角色是否存在
        Integer rankIdOne = this.baseMapper.selectRankId(rankId);
        if (rankIdOne == null) {
            return Result.fail(ErrorCode.ERROR_NAME_RANKIDISNULL);
        }

        if (!Strings.isEmpty(loginAccount) && !Strings.isEmpty(phone) && !Strings.isEmpty(rankId)) {
            //判断账号重复
            LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(!Strings.isEmpty(loginAccount), Admin::getLoginAccount, loginAccount).last("limit 1");
            Admin one = this.baseMapper.selectOne(wrapper);
            if (one != null) {
                return Result.fail(ErrorCode.ERROR_NAME_LOGiNACCOUNT);
            }
            //判断手机号格式
            if (!Pattern.matches("1\\d{10}(\\.000000)?", phone)) {
                return Result.fail(ErrorCode.ERROR_NAME_PHONE_NOFORMAT);
            }
            //判断手机号重复
            LambdaQueryWrapper<Admin> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(!Strings.isEmpty(phone), Admin::getPhone, phone).last("limit 1");
            Admin phoneOne = this.baseMapper.selectOne(wrapper1);
            if (phoneOne != null) {
                return Result.fail(ErrorCode.ERROR_TEL_DUPLICATE);
            }
//            //判断角色是否存在
//            Integer rankIdOne = this.baseMapper.selectRankId(rankId);
//            if (rankIdOne == null) {
//                return Result.fail(ErrorCode.ERROR_NAME_RANKIDISNULL);
//            }
            Integer lastUserId = this.baseMapper.selectLastById();
            Admin admin = new Admin();
            admin.setUserId(lastUserId + 1);
            admin.setLoginAccount(loginAccount);
            admin.setStatus(1);
            admin.setPhone(phone);
            admin.setRankId(rankId);
            int row = this.baseMapper.insert(admin);
            if (row <= 0) {
                return Result.fail(ErrorCode.ERROR_ADD);
            }
        } else {
            return Result.fail(789, "无添加的数据");
        }
        return Result.success(ErrorCode.SUCCESS);
    }

    /**
     * 修改管理员
     *
     * @param jsonObject
     * @return
     * @throws ParseException
     */
    @Override
    public Result editSave(JSONObject jsonObject) throws ParseException {

        String userId = jsonObject.getString("userId");
        if (!StringUtils.isEmpty(userId)){
            LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Admin::getUserId,Integer.valueOf(userId)).last("limit 1");
            Admin admin = this.baseMapper.selectOne(wrapper);
            if (admin==null){
                return Result.fail(0,"用户不存在");
            }
        }

        if (StringUtils.isEmpty(userId)) {
            return Result.fail(321321, "当前用户不存在");
        }
        String loginAccount = jsonObject.getString("loginAccount");
        String phone = jsonObject.getString("phone");
        String rankId = jsonObject.getString("rankId");
        if (StringUtils.isEmpty(loginAccount)){
            return Result.fail(0,"账户不能为空");
        }
        if (StringUtils.isEmpty(phone)){
            return Result.fail(0,"手机号不能为空");
        }
        if (StringUtils.isEmpty(rankId)){
            return Result.fail(0,"角色不能为空");
        }
        System.out.println(phone);
        System.out.println(jsonObject);
        if (!StringUtils.isEmpty(phone)) {
            //判断手机号格式
            if (!Pattern.matches("1\\d{10}(\\.000000)?", phone)) {
                return Result.fail(ErrorCode.ERROR_NAME_PHONE_NOFORMAT);
            }
            //判断手机号重复
            Integer phoneId = this.baseMapper.varLidatephoneById(userId, phone);
            System.out.println("phoneId = " + phoneId);
            if (phoneId != null) {
                return Result.fail(ErrorCode.ERROR_TEL_DUPLICATE);
            }
        }
        if (loginAccount != null) {
            //判断账号重复
            Integer ID = this.baseMapper.varLidateLoginAccount(userId, loginAccount);
            if (ID != null) {
                return Result.fail(ErrorCode.ERROR_NAME_LOGiNACCOUNT);
            }
        }

        if (rankId != null) {
            //判断角色是否存在
            Integer rankIdOne = this.baseMapper.selectRankId(rankId);
            if (rankIdOne == null) {
                return Result.fail(ErrorCode.ERROR_NAME_RANKIDISNULL);
            }
        }
        Admin admin = new Admin();
        admin.setUserId(Integer.valueOf(userId));
        admin.setLoginAccount(loginAccount);
        admin.setPhone(phone);
        admin.setRankId(rankId);
        int row = this.baseMapper.updateById(admin);
        if (row > 0) {
            return Result.fail(ErrorCode.SUCCESS);
        } else {
            return Result.fail(ErrorCode.ERROR_ADD);
        }
    }

    /**
     * 删除管理员
     *
     * @param ids
     * @return
     */
    @Override
    public Result deleteByIds(Integer[] ids) {

        StringBuilder sb = new StringBuilder();
        System.out.println("Arrays.toString(ids) = " + Arrays.toString(ids));
        if (ids.length > 0) {
            for (Integer id : ids) {
                if (id != null) {
                    Admin admin = this.baseMapper.selectById(id);
                    if (admin == null) {
                        sb.append(id).append("为主键的用户不存在,");
                    }
                    this.baseMapper.updateCommentById(id);
                    this.baseMapper.updateAdminApplyById(id);
                    this.baseMapper.updateChannelById(id);
                    this.baseMapper.updateChannelApplyById(id);
                    this.baseMapper.updateChannelAdminApplyById(id);
                    this.baseMapper.updateChannelCommentById(id);
                    this.baseMapper.updateChannelMissionById(id);
                    this.baseMapper.updatemerchantById(id);
                    this.baseMapper.updatemerChantApplyById(id);
                    this.baseMapper.updatemerChantCashApplyById(id);
                    this.baseMapper.updateMerChantChargeById(id);
                    this.baseMapper.updateMissionById(id);
                    this.baseMapper.updateMissionApplyById(id);
                    keeperWithdrawalsMapper.updateUserId(String.valueOf(id));
                    int row = super.baseMapper.deleteById(id);
                }
            }
        } else {
            return Result.fail(ErrorCode.ERROR_DELETE);
        }
        if (sb.length() > 0) {
            String s = sb.toString();
            System.out.println("substring = " + s.substring(0, s.lastIndexOf(",") - 1));
            return Result.fail(0, s.substring(0, s.lastIndexOf(",")));
        }

        return Result.success(ErrorCode.SUCCESS);
    }

}





